import router from './router'
import config from '../../config'
import qs from 'querystring'
import tool from './tool'
import axios from 'axios'
import formatRequestResult from './formatRequestResult'
import requestFakeData from './requestFakeData'
import { ElNotification } from 'element-plus'
import event from './event'
import { useStore } from './store'
import DataRecovery from './dataRecovery'


let ld = null

// class content_left {
//     handleSelect = () => { }
//     data = []
//     constructor(handleSelect) {
//         this.handleSelect = handleSelect
//     }
//     async init() {
//         let re = await to.requestData('/archive-search', {}, {}, 'get')
//         if (re.status) {
//             this.data = re.data
//         } else {
//             throw re.content
//         }
//     }
// }

const to = {
    config,
    document: document,
    array: {
        delete: {
            byIndex(arr = [], index = -1) {
                if (check.isArray(arr) == false) {
                    check.throwError('arr应为数组')
                }
                if (check.isInt(index) == false) {
                    check.throwError('index应为整数')
                }
                return [...arr.slice(0, index), ...arr.slice(index + 1)]
            },
            byKeyValue(arr = [], key = '', value = undefined) {
                if (check.isArray(arr) == false) {
                    check.throwError('arr应为数组')
                }
                return arr.filter(item => item[key] != value)
            },
            byValue(arr = [], value = undefined) {
                if (check.isArray(arr) == false) {
                    check.throwError('arr应为数组')
                }
                return arr.filter(item => item != value)
            },
            clearUndefined(arr = []) {
                if (check.isArray(arr) == false) {
                    check.throwError('arr应为数组')
                }
                return arr.filter(item => item != undefined)
            }
        },
        async format(arr = [], func = async (e) => { return e }) {
            if (check.isArray(arr) == false) {
                check.throwError('arr应为数组')
            }
            for (let i = 0; i < arr.length; i++) {
                arr[i] = await func(arr[i])
            }
            return arr
        },
        async for(arr = [], func = async (e) => { return e }) {
            if (check.isArray(arr) == false) {
                check.throwError('arr应为数组')
            }
            for (let i = 0; i < arr.length; i++) {
                await func(arr[i])
            }
        },
        count(arr, value) {
            let re = 0
            for (let i = 0; i < arr.length; i++) {
                if (arr[i] === value) re++
            }
            return re
        },
        getFirstIndex: {
            byKeyValue(arr = [], key = '', value = undefined) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i][key] === value) return i
                }
                return -1
            }
        }
    },
    object: {
        async format(obj = {}, func = async (key, value) => { return value }) {
            for (let i = 0; i < Object.keys(obj).length; i++) {
                obj[Object.keys(obj)[i]] = await func(Object.keys(obj)[i], obj[Object.keys(obj)[i]])
            }
            return obj
        },
        async for(obj = {}, func = async (key, value) => { return value }) {
            for (let i = 0; i < Object.keys(obj).length; i++) {
                await func(Object.keys(obj)[i], obj[Object.keys(obj)[i]])
            }
        },
    },
    string: {
        delete: {
            bySubString(string, subString) {
                string = string.split(subString)
                let re = ''
                for (let i = 0; i < string.length; i++) {
                    re += string[i]
                }
                return re
            }
        }
    },
    JSON: {
        parse(string) {
            try {
                return JSON.parse(string)
            } catch (error) {
                return string
            }
        },
        stringify(obj) {
            return JSON.stringify(obj)
        }
    },
    sliceByPageSize(arr, page, size) {
        return arr.slice((page - 1) * size, page * size)
    },
    event,
    wait(n) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve()
            }, n * 1000);
        })
    },
    loading: {
        c: 0,
        _: null,
        show() {
            // this._ = Loading({
            //     lock: true,
            //     text: '请稍候',
            //     spinner: 'el-icon-loading',
            //     background: 'rgba(255, 255, 255, 0.6)'
            // });
            to.event.setItem('controlLoadingMask', true)
            this.c++
        },
        async hide() {
            // await tool.wait(0.05)
            this.c--
            if (!this.c) {
                to.event.setItem('controlLoadingMask', false)
                // this._.close()
            }
        }
    },
    async requestData(apiName = '', query = {}, param = {}, method = 'post', loading = true) {
        let query_c = this.deepCopyObject(query)
        if (loading) {
            this.loading.show()
        }
        return new Promise(async (resolve, reject) => {
            const requestResult = async (e) => {
                try {
                    console.log('请求 - 结束', e.data)
                    let re = await formatRequestResult(apiName, e.data, query_c, param, method)
                    resolve(re)
                } catch (error) {
                    reject(`${error}`)
                }
                if (loading) {
                    this.loading.hide()
                }
            }
            let fakeData = requestFakeData.getFakeData(apiName)
            if (fakeData === undefined) {
                console.log('请求 - 开始', apiName, 'query：', query, 'param：', param, method)
                await tool.flow(async () => {
                    if (method == 'get') {
                        let re = await axios.get(config.serverURL + apiName + (tool.isObjectBlank(query) ? '' : `?${typeof (query) == 'string' ? query : qs.stringify(query)}`), {
                            headers: {
                                token: tool.event.getItem('token')
                            }
                        })
                        await requestResult(re)
                    } else if (method == 'post') {
                        let re = await axios.post(config.serverURL + apiName + (tool.isObjectBlank(query) ? '' : `?${typeof (query) == 'string' ? query : qs.stringify(query)}`), param, {
                            headers: {
                                token: tool.event.getItem('token')
                            }
                        })
                        await requestResult(re)
                    } else if (method == 'put') {
                        let re = await axios.put(config.serverURL + apiName + (tool.isObjectBlank(query) ? '' : `?${typeof (query) == 'string' ? query : qs.stringify(query)}`), param, {
                            headers: {

                                token: tool.event.getItem('token')
                            }
                        })
                        await requestResult(re)
                    } else if (method == 'delete') {
                        let re = await axios.delete(config.serverURL + apiName + (tool.isObjectBlank(query) ? '' : `?${typeof (query) == 'string' ? query : qs.stringify(query)}`), { data: param, headers: { token: tool.event.getItem('token') } })
                        await requestResult(re)
                    }
                }, (err) => {
                    console.log(err)
                    requestResult({
                        data: {
                            status: 0,
                            content: `请求失败`
                        }
                    })
                })
            } else {
                await tool.wait(0.5)
                requestResult({
                    data: {
                        status: 1,
                        content: 'success',
                        data: fakeData
                    }
                })
            }
        })
    },
    getElementPositionAndSizeById(elementId) {
        const element = document.getElementById(elementId);
        if (!element) {
            throw new Error(`Element with id "${elementId}" not found`);
        }

        const rect = element.getBoundingClientRect();
        const x = rect.left + window.scrollX;
        const y = rect.top + window.scrollY;
        const width = rect.width;
        const height = rect.height;

        return {
            x,
            y,
            width,
            height,
            windowWidth: document.body.clientWidth,
            windowHeight: document.body.clientHeight
        };
    },
    deepCopyObject(obj) {
        try {
            return JSON.parse(JSON.stringify(obj))
        } catch (error) {
            return undefined
        }
    },
    getStringHighlight(string, subStrings) {
        function findFirstUniqueIndices(longStr, substrings) {
            let usedIndices = new Set();
            let indices = [];

            // 遍历每个子字符串
            substrings.forEach(sub => {
                let pos = longStr.indexOf(sub);  // 查找子字符串首次出现的位置

                while (pos !== -1) {
                    let canUse = true;
                    // 检查该子字符串的所有字符的索引是否已被使用
                    for (let i = 0; i < sub.length; i++) {
                        if (usedIndices.has(pos + i)) {
                            canUse = false;  // 如果有任何字符索引被使用，跳过这个位置
                            break;
                        }
                    }

                    if (canUse) {
                        // 如果可以使用，存储每个字符的索引
                        for (let i = 0; i < sub.length; i++) {
                            indices.push(pos + i);
                            usedIndices.add(pos + i);  // 标记这些索引为已使用
                        }
                        break;  // 确保只记录首次出现的位置
                    }

                    // 查找下一个匹配位置
                    pos = longStr.indexOf(sub, pos + 1);
                }
            });

            // 返回按索引顺序排列的数组
            return indices.sort((a, b) => a - b);
        }
        subStrings = findFirstUniqueIndices(string, subStrings)
        if (subStrings == undefined) subStrings = []
        let sbust = []
        for (let i = 0; i < subStrings.length; i++) {
            if (subStrings[i] == null) continue
            sbust.push(parseInt(subStrings[i]))
        }
        subStrings = sbust
        let re1 = []
        string = string.split('')
        for (let i = 0; i < string.length; i++) {
            if (re1.length == 0) {
                re1.push({
                    flag: subStrings.indexOf(i) == -1 ? false : true,
                    text: string[i]
                })
            } else {
                if (((subStrings.indexOf(i - 1) == -1 && subStrings.indexOf(i) == -1) || (subStrings.indexOf(i - 1) != -1 && subStrings.indexOf(i) != -1)) == false) {
                    re1.push({
                        flag: subStrings.indexOf(i) == -1 ? false : true,
                        text: string[i]
                    })
                } else {
                    re1[re1.length - 1].text += string[i]
                }
            }
        }
        return re1
    },
    changeJSNameToCSSName(string) {
        string = string.split('')
        let re = ''
        for (let i = 0; i < string.length; i++) {
            let c = string[i].charCodeAt(0)
            if (c <= 90 && c >= 65) {
                re += '-'
                re += String.fromCharCode(c + 32)
            } else {
                re += string[i]
            }
        }
        return re
    },
    changeJSObjToCSSStyleString(JSObj) {
        let res = ''
        for (let i = 0; i < Object.keys(JSObj).length; i++) {
            res += `${this.changeJSNameToCSSName(Object.keys(JSObj)[i])}: ${JSObj[Object.keys(JSObj)[i]]};`
        }
        return res
    },
    getStringHTML(highLightArr = [], highLightStyle = {}) {
        let re = ''
        for (let i = 0; i < highLightArr.length; i++) {
            if (highLightArr[i].flag) {
                re += `<span style="${this.changeJSObjToCSSStyleString(Object.assign({
                    color: 'inherit',
                    fontSize: 'inherit',
                    fontWeight: 'inherit',
                    fontStyle: 'inherit',
                    fontFamily: 'inherit',
                    backgroundColor: 'inherit',
                    userSelect: 'text'
                }, highLightStyle))}" >${highLightArr[i].text}</span>`
            } else {
                re += `<span style="${this.changeJSObjToCSSStyleString({
                    color: 'inherit',
                    fontSize: 'inherit',
                    fontWeight: 'inherit',
                    fontStyle: 'inherit',
                    fontFamily: 'inherit',
                    backgroundColor: 'inherit',
                    userSelect: 'text'
                })}" >${highLightArr[i].text}</span>`
            }
        }
        return re
    },
    getStringHighlightedHTML(string = '', subStrings = [], highLightStyle = {}) {
        return this.getStringHTML(this.getStringHighlight(string, subStrings), highLightStyle)
    },
    handleNotLogin() {
        router.push('/login')
    },
    isObjectBlank(o) {
        if (typeof (o) == 'string') return false
        return Object.keys(o).length == 0
    },
    async flow(fn, handleError, args = []) {
        try {
            return await fn(...args)
        } catch (error) {
            handleError(error)
        }
    },
    throwError(str) {
        throw str
    },
    toast: {
        success(content) {
            ElNotification({
                title: '成功',
                message: content,
                type: 'success',
            })
        },
        warning(content) {
            ElNotification({
                title: '警告',
                message: content,
                type: 'warning',
            })
        },
        info(content) {
            ElNotification({
                title: '提示',
                message: content,
                type: 'info',
            })
        },
        error(content) {
            ElNotification({
                title: '错误',
                message: content,
                type: 'error',
            })
        }
    },
    async execFunc(fn = async () => { }) {
        return await fn()
    },
    getHighLightHTML(str, substring) {
        if (!substring) {
            return `<span style="color: blue;user-select:text">${str}</span>`;
        }
        // 如果 substring 是数组，逐个处理
        if (Array.isArray(substring)) {
            return substring.reduce((acc, sub) => {
                const escapedSubstring = sub.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');  // 转义正则特殊字符
                const regex = new RegExp(`(${escapedSubstring})`, 'gi');  // 创建正则，匹配大小写不敏感
                acc = acc.replace(regex, `<span style="color: red;user-select:text">$1</span>`);  // 替换为红色标记
                return acc;
            }, str)
                .replace(/(^|<\/span>)([^<]+)(<|$)/g, '$1<span style="color: blue;user-select:text">$2</span>$3'); // 其余部分保持蓝色
        } else {
            // substring 是单个字符串，直接处理
            const escapedSubstring = substring.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');  // 转义正则特殊字符
            const regex = new RegExp(`(${escapedSubstring})`, 'gi');  // 创建正则，匹配大小写不敏感
            return str.replace(regex, `<span style="color: red;user-select:text">$1</span>`)  // 替换为红色标记
                .replace(/(^|<\/span>)([^<]+)(<|$)/g, '$1<span style="color: blue;user-select:text">$2</span>$3'); // 其余部分保持蓝色
        }
    },
    async formatDataObjToString(obj, toMultiple = []) {
        let re = ''
        let flag = true
        await tool.object.for(obj, async (k, v) => {
            if (toMultiple.indexOf(k) + 1) {
                await tool.array.for(v, (e) => {
                    if (flag) {
                        flag = false
                    } else {
                        re += '&'
                    }
                    re += `${k}=${e}`
                })
            } else {
                if (flag) {
                    flag = false
                } else {
                    re += '&'
                }
                re += `${k}=${v}`
            }
        })
        return re
    },
    async getContentHTML(item, substring) {
        const store = useStore()
        let dict = store.searchDictByFieldArr(Object.keys(item)).sort((a, b) => {
            return a.field > b.field
        })
        let re = ''
        await tool.array.for(dict, (e) => {
            re += `<span style="user-select:text" >${e.title}：</span>${this.getHighLightHTML(item[e.field] ? `${item[e.field]}` : '', substring)}<span style="margin-right:10px;user-select:text" ></span>`
        })
        return re
    },
    getTotalPageByPageSize(size, total) {
        return parseInt(total / size) + (total % size ? 1 : 0)
    },
    cControls: {
        getSplit() {
            return [
                {
                    type: 'label',
                    title: '|',
                    style: {
                        scale: 0.9,
                        color: 'rgb(200, 200, 200)',
                        transform: 'translateY(-2px)',
                        display: 'inline-block'
                    }
                },
            ]
        },
        pageSizeObject(
            getPage = () => { },
            getSize = () => { },
            getTotal = () => { },
            requestData = async (to) => { },
            setForm = (e) => { },
            setData = (e) => { },
            refreshPage = () => { }
        ) {
            return {
                currentLefts() {
                    let re = []
                    let t = getPage() - 1
                    while (t && Math.abs(t - getPage()) < 6) {
                        re.push(t)
                        t--
                    }
                    return re
                },
                currentRights() {
                    let re = []
                    let t = getPage() + 1
                    while (t <= tool.getTotalPageByPageSize(getSize(), getTotal()) && Math.abs(t - getPage()) < 6) {
                        re.push(t)
                        t++
                    }
                    return re
                },
                total() {
                    return tool.getTotalPageByPageSize(getSize(), getTotal())
                },
                current() {
                    return getPage()
                },
                async handleChange(to) {
                    if (!to) to = getPage()
                    await tool.flow(async () => {
                        // let re = await data.get(Object.assign(data.form, {
                        //     currentPage: to
                        // }))
                        let re = await requestData(to)
                        setData({})
                        refreshPage()
                        await tool.wait(0.001)
                        setData(re)
                        // data.data = re
                        setForm(to)
                        // data.form = Object.assign(data.form, {
                        //     currentPage: to
                        // })
                        refreshPage()
                    }, err => tool.toast.error(`${err}`))
                }
            }
        },
        async pageSizeControls(
            getTotal = () => { },
            getCurrentPage = () => { },
            handleChange = async (to) => { },
            refreshPage = () => { },
            getCurrentLefts = () => { },
            getCurrentRights = () => { },
            setCurrentPage = (e) => { },
            getSize = () => { },
            setSize = (e) => { }
        ) {
            const getTotalPage = () => {
                return tool.getTotalPageByPageSize(getSize(), getTotal())
            }
            return [
                {
                    type: 'label',
                    title: `共${getTotal()}个，${getTotalPage()}页`,
                    style: {
                        fontSize: '14px',
                        color: '#409eff'
                    }
                },
                ...tool.cControls.getSplit(),
                {
                    type: 'button',
                    title: '<< 第一页',
                    disabled: getCurrentPage() == 1,
                    callBack: async () => {
                        await handleChange(1)
                        refreshPage()
                    }
                },
                {
                    type: 'button',
                    title: '< 上一页',
                    disabled: getCurrentPage() == 1,
                    callBack: async () => {
                        await handleChange(getCurrentPage() - 1)
                        refreshPage()
                    }
                },
                ...await tool.execFunc(async () => {
                    let re = [...getCurrentLefts(), getCurrentPage(), ...getCurrentRights()].sort((a, b) => {
                        return a - b
                    })
                    await tool.array.format(re, async (item) => {
                        return {
                            type: 'button',
                            title: item,
                            style: {
                                type: item == getCurrentPage() ? 'primary' : ''
                            },
                            callBack: async () => {
                                if (item == getCurrentPage()) return
                                await handleChange(item)
                                refreshPage()
                            }
                        }
                    })
                    return re
                }),
                {
                    type: 'button',
                    title: '下一页 >',
                    disabled: getCurrentPage() >= getTotalPage(),
                    callBack: async () => {
                        await handleChange(getCurrentPage() + 1)
                        refreshPage()
                    }
                },
                {
                    type: 'button',
                    title: '最后一页 >>',
                    disabled: getCurrentPage() >= getTotalPage(),
                    callBack: async () => {
                        await handleChange(getTotalPage())
                        refreshPage()
                    }
                },
                ...tool.cControls.getSplit(),
                {
                    type: 'label',
                    title: `转到`,
                    style: {
                        fontSize: '14px',
                        color: 'gray'
                    }
                },
                {
                    type: 'input',
                    default: '',
                    disabled: false,
                    placeholder: '页码',
                    icon: 'switch',
                    style: {
                        width: '60px'
                    },
                    inputCallBack: (e) => {

                    },
                    okCallBack: async (e) => {
                        if (e == '') return
                        if (isNaN(e)) {
                            tool.toast.error(`页码应为正整数且不能大于${getTotalPage()}`)
                            return
                        }
                        if (e < 1 || e > getTotalPage()) {
                            refreshPage()
                            tool.toast.error(`页码应为正整数且不能大于${getTotalPage()}`)
                            return
                        }
                        setCurrentPage(parseInt(e))
                        await handleChange(parseInt(e))
                        refreshPage()
                    }
                },
                {
                    type: 'label',
                    title: `每页个数`,
                    style: {
                        fontSize: '14px',
                        color: 'gray'
                    }
                },
                {
                    type: 'select',
                    options: [
                        5, 10, 15, 20, 100, 300, 500, 1000, 5000, 10000, 100000
                    ],
                    placeholder: '',
                    default: getSize(),
                    style: {
                        width: '100px'
                    },
                    callBack: async (e) => {
                        setSize(e)
                        await handleChange(1)
                        refreshPage()
                    }
                },
                ...tool.cControls.getSplit(),
                {
                    type: 'button',
                    title: '刷新',
                    leftIcon: 'reset',
                    callBack: async () => {
                        await handleChange(getCurrentPage())
                        refreshPage()
                    }
                }
            ]
        },
        button({
            title = '',
            leftIcon = '',
            rightIcon = '',
            plain = false,
            type = '',
            disabled = false,
            callBack = () => { }
        }) {
            return {
                type: 'button',
                title,
                leftIcon,
                rightIcon,
                style: {
                    plain,
                    type
                },
                disabled,
                callBack
            }
        },
        label({
            title = '',
            style = {}
        }) {
            return {
                type: 'label',
                title,
                style: Object.assign({
                    fontSize: '14px',
                    color: '#333'
                }, style)
            }
        },
        table({
            list = [],
            form = [],
            enableSelect = false,
            callBack = () => { },
            operationGetter = () => { },
            isSelectedChecker = (value) => { },
            checkIsSelectedKey = 'id',
        }) {
            return {
                type: 'table',
                enableSelect,
                form,
                list: (() => {
                    for (let i = 0; i < list.length; i++) {
                        try {
                            list[i]._selected = isSelectedChecker(list[i][checkIsSelectedKey])
                        } catch (error) {

                        }
                        try {
                            list[i].op = operationGetter(list[i])
                        } catch (error) {

                        }
                    }
                    return list
                })(),
                callBack
            }
        },
        list({
            list = [],
            enableSelect = false,
            callBack = () => { },
            operationGetter = () => { },
            isSelectedChecker = (value) => { },
            checkIsSelectedKey = 'id',
        }) {
            return {
                type: 'list',
                enableSelect,
                list: (() => {
                    for (let i = 0; i < list.length; i++) {
                        try {
                            list[i]._selected = isSelectedChecker(list[i][checkIsSelectedKey])
                        } catch (error) {

                        }
                        try {
                            list[i].operations = operationGetter(list[i])
                        } catch (error) {

                        }
                    }
                    return list
                })(),
                callBack
            }
        },
        left: {
            categoryMenu() {
                const left = {
                    data: [],
                    async get() {
                        let re = await tool.requestData('/archive-search', {}, {}, 'get')
                        if (re.status) {
                            this.data = re.data
                        } else {
                            throw re.content
                        }
                    },
                    // async handleSelect(item) {
                    //     if (!item.isDir) {
                    //         this.selectedItem = undefined
                    //         await tool.wait(0.01)
                    //         this.selectedItem = item;
                    //         (() => {
                    //             for (let i = 0; i < this.data.length; i++) {
                    //                 for (let i1 = 0; i1 < this.data[i].children.length; i1++) {
                    //                     if (this.data[i].children[i1].name == item.name) {
                    //                         this.selectedItemParent = this.data[i]
                    //                         return
                    //                     }
                    //                 }
                    //             }
                    //         })()
                    //         try {
                    //             selectCallBack(this.selectedItem, this.selectedItemParent)
                    //         } catch (error) {

                    //         }
                    //     }
                    // },
                    selectedItem: undefined,
                    selectedItemParent: undefined
                }
                return {
                    async init() {
                        await left.get()
                    },
                    getSelectedItem: () => left.selectedItem,
                    getSelectedItemParent: () => left.selectedItemParent,
                    getData: () => left.data
                }
            }
        },
        mSelectObject() {
            let list = []
            return {
                add(ids) {
                    if (ids instanceof Array) {
                        list = [...list, ...ids]
                    } else {
                        list.push(ids)
                    }
                    list = [...new Set(list)]
                },
                remove(id) {
                    list = list.filter(item => item !== id)
                },
                is(id) {
                    return list.indexOf(id) + 1
                },
                removeAll() {
                    list = []
                },
                getList() {
                    return list
                },
                setList(e) {
                    list = e
                }
            }
        },
        mSelectControls(
            getSelectedIds = () => { },
            setSelectedIds = (e) => { },
            refreshPage = () => { },
            functions = [
                {
                    title: '',
                    leftIcon: '',
                    callBack() {

                    }
                }
            ],
            getCurrentPageIds = () => { }
        ) {
            if (getCurrentPageIds().length === 0 && getSelectedIds().length === 0) return []
            return [
                ...tool.cControls.getSplit(),
                ...(() => {
                    if (getSelectedIds().length) {
                        return [
                            {
                                type: 'label',
                                title: `已选${getSelectedIds().length}个`,
                                style: {
                                    color: '#409eff',
                                    fontSize: '14px'
                                }
                            },
                        ]
                    } else {
                        return []
                    }
                })(),
                ...(() => {
                    return [
                        ...(() => {
                            let currentPageIds = getCurrentPageIds()
                            let selectedIds = getSelectedIds()
                            for (let i = 0; i < currentPageIds.length; i++) {
                                let flag = true
                                for (let i1 = 0; i1 < selectedIds.length; i1++) {
                                    if (currentPageIds[i] === selectedIds[i1]) {
                                        flag = false
                                        break
                                    }
                                }
                                if (flag) {
                                    return [{
                                        type: 'button',
                                        title: '当前页全选',
                                        leftIcon: 'selectAll',
                                        callBack: async () => {
                                            setSelectedIds(getCurrentPageIds())
                                            refreshPage()
                                        },
                                        style: {
                                            type: '',
                                            plain: false
                                        },
                                        disabled: false,
                                    },]
                                }
                            }
                            return [

                            ]
                        })(),
                        {
                            type: 'button',
                            title: '当前页全反选',
                            leftIcon: 'backSelect',
                            callBack: async () => {
                                let currentSelectedIds = tool.deepCopyObject(getSelectedIds())
                                let currentPageIds = getCurrentPageIds()
                                currentPageIds.forEach(item => {
                                    if (currentSelectedIds.indexOf(item) + 1) {
                                        currentSelectedIds = currentSelectedIds.filter(item1 => item1 != item)
                                    } else {
                                        currentSelectedIds.push(item)
                                    }
                                })
                                setSelectedIds(currentSelectedIds)
                                refreshPage()
                            },
                            style: {
                                type: '',
                                plain: false
                            },
                            disabled: false,
                        },

                        ...(() => {
                            if (getSelectedIds().length) {
                                return [
                                    {
                                        type: 'button',
                                        title: '取消多选',
                                        leftIcon: 'close',
                                        callBack: async () => {
                                            setSelectedIds([])
                                            refreshPage()
                                        },
                                        style: {
                                            type: 'danger',
                                            plain: false
                                        },
                                        disabled: false,
                                    },
                                ]
                            } else {
                                return []
                            }
                        })(),
                    ]
                })(),
                ...(() => {
                    if (getSelectedIds().length && functions.length) {
                        return [
                            ...tool.cControls.getSplit(),
                            ...(() => {
                                for (let i = 0; i < functions.length; i++) {
                                    functions[i] = {
                                        ...functions[i],
                                        type: 'button',
                                        style: {
                                            type: '',
                                            plain: false
                                        },
                                        disabled: false,
                                    }
                                }
                                return functions
                            })()
                        ]
                    } else {
                        return []
                    }
                })()
            ]
        },
        settings: {
            label(text) {
                return {
                    type: 'label',
                    text
                }
            },
            button(text, callBack = () => { }, rightType = '', rightValue = false) {
                return {
                    type: 'button',
                    text,
                    rightType,
                    rightValue,
                    callBack
                }
            },
            buttonGroup(title = '', list = []) {
                return {
                    type: 'buttonGroup',
                    title,
                    list
                }
            }
        }
    },
    preview: {
        archive(item) {
            const store = useStore()
            store.showFormDialog('案卷详细信息', [], store.searchDictByFieldArr(Object.keys(item)), item, false, () => { store.hideFormDialog() }, false, () => { }, () => { }, true)
        },
        inside(item) {
            const store = useStore()
            store.showFormDialog('卷内详细信息', [], store.searchDictByFieldArr(Object.keys(item)), item, false, () => { store.hideFormDialog() }, false, () => { }, () => { }, true)
        }
    },
    resize: {
        init() {
            if (!localStorage.getItem('leftMenuWidth')) localStorage.setItem('leftMenuWidth', '240px')
            if (!localStorage.getItem('mainType1LeftTreeWidth')) localStorage.setItem('mainType1LeftTreeWidth', '310px')
            if (!localStorage.getItem('mainType1ContentTabHeight')) localStorage.setItem('mainType1ContentTabHeight', '400px')
        },
        get: {
            leftMenuWidth() {
                return localStorage.getItem('leftMenuWidth')
            },
            mainType1LeftTreeWidth() {
                return localStorage.getItem('mainType1LeftTreeWidth')
            },
            mainType1ContentTabHeight() {
                return localStorage.getItem('mainType1ContentTabHeight')
            },
        },
        set: {
            leftMenuWidth(value) {
                localStorage.setItem('leftMenuWidth', value)
            },
            mainType1LeftTreeWidth(value) {
                localStorage.setItem('mainType1LeftTreeWidth', value)
            },
            mainType1ContentTabHeight(value) {
                localStorage.setItem('mainType1ContentTabHeight', value)
            },
        }
    },
    formatDate3(date, dateOnly = false) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');  // 月份从0开始，+1调整
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
        if (dateOnly) {
            return `${year}-${month}-${day}`;
        }
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    async getCategoryList() {
        let re = await tool.requestData('/archive-search', {}, {}, 'get')
        if (re.status) {
            return re.data
        } else {
            throw re.content
        }
    },
    async selectFile(allowedFormats = []) {
        return new Promise((resolve, reject) => {
            const input = document.createElement('input');
            input.type = 'file';
            if (allowedFormats.length > 0) {
                input.accept = allowedFormats.map(ext => `.${ext}`).join(',');
            }
            input.onchange = async (event) => {
                const file = event.target.files[0];
                if (!file) {
                    reject(new Error('No file selected'));
                    return;
                }
                const fileExtension = file.name.split('.').pop().toLowerCase();
                if (allowedFormats.length > 0 && !allowedFormats.includes(fileExtension)) {
                    reject(new Error(`Invalid file format. Allowed formats: ${allowedFormats.join(', ')}`));
                    return;
                }
                try {
                    const formData = new FormData();
                    formData.append('file', file);
                    const blobURL = URL.createObjectURL(file);
                    resolve({
                        file,
                        formData,
                        blobURL
                    });
                } catch (error) {
                    reject(error);
                }
            };
            input.onerror = (error) => {
                reject(error);
            };
            input.click();
        });
    },
    async handleSelectExcelFile() {
        return await this.selectFile(['xls', 'xlsx'])
    },
    async createFileFormData(fileObj = undefined, otherParams = {}) {
        if (!fileObj) throw '无文件'
        let data = new FormData()
        data.append('file', fileObj)
        await tool.object.for(otherParams, (k, v) => {
            data.append(k, v)
        })
        return data
    },
    async uploadFile(apiName, data) {
        return new Promise((resolve, reject) => {
            var config1 = {
                method: 'post',
                url: `${config.serverURL}${apiName}`,
                headers: {

                },
                data: data
            };
            tool.loading.show()
            axios(config1)
                .then(function (response) {
                    tool.loading.hide()
                    resolve(response.data)
                    console.log(JSON.stringify(response.data));
                })
                .catch(function (error) {
                    tool.loading.hide()
                    reject(error)
                    console.log(error);
                });
        })
    },
    async getCategoryFields(categoryId) {
        let re = await tool.requestData(`/archive-collection/category-fields/${categoryId}`, {}, {}, 'get')
        if (re.status) {
            return re.data
        } else {
            throw re.content
        }
    },
    DataRecovery,
    async changeObjectToString(obj) {
        let re = ''
        await tool.object.for(obj, (k, v) => {
            re += `<div>${k}：${v}</div>`
        })
        return re
    },
    autoGenValue(builder, value, split = '-') {
        let re = ''
        for (let i = 0; i < builder.length; i++) {
            if (i) re += split
            re += `${value[builder[i]]}`
        }
        return re
    },
    getBuilderArr(builderStr) {
        try {
            return builderStr.split('-')
        } catch (error) {
            return []
        }
    },
    objectKeyToCamelCase(obj) {
        if (Array.isArray(obj)) {
            return obj.map(item => this.objectKeyToCamelCase(item));  // 递归处理数组
        } else if (obj !== null && typeof obj === 'object') {
            const newObj = {};
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    // 转换键为小驼峰格式
                    const camelKey = key.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
                    newObj[camelKey] = this.objectKeyToCamelCase(obj[key]);  // 递归处理值
                }
            }
            return newObj;
        }
        return obj;  // 返回原值（当值为基本数据类型时）
    },
    selectValueOfObjectByKey(arr = [], key = '') {
        let re = []
        for (let i = 0; i < arr.length; i++)re.push(arr[i][key])
        return re
    },
    location,
    localStorage,
    updateClock() {
        const now = new Date();

        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const time = `${hours}:${minutes}:${seconds}`;

        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const fullDate = `${year}-${month}-${day}`;

        const weekdays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const weekday = weekdays[now.getDay()];

        return `${fullDate} ${weekday} ${time}`;
    },
    getTextWidth(text, fontSizePx, fontFamily = 'Arial') {
        try {
            if (typeof (text) !== 'string') text = this.JSON.stringify(text)
        } catch (error) {
            text = `${text}`
        }
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        context.font = `${fontSizePx}px ${fontFamily}`;
        return Number(context.measureText(text).width);
    },
    async selectFiles(allowedExtensions = [], maxCount = 5) {
        return new Promise((resolve, reject) => {
            // 创建一个隐藏的文件输入元素
            const input = document.createElement('input');
            input.type = 'file';
            input.multiple = true;
            input.accept = allowedExtensions.map(ext => '.' + ext).join(',');
            input.style.display = 'none';

            // 添加到文档并触发点击事件
            document.body.appendChild(input);
            input.click();

            input.addEventListener('change', async () => {
                const files = Array.from(input.files);
                document.body.removeChild(input); // 移除输入元素

                if (files.length === 0) {
                    return resolve([]);
                }

                // 过滤文件扩展名
                const filteredFiles = files.filter(file => {
                    const ext = file.name.split('.').pop().toLowerCase();
                    return allowedExtensions.length === 0 || allowedExtensions.includes(ext);
                }).slice(0, maxCount);

                // 读取文件内容
                const results = await Promise.all(filteredFiles.map(async file => {
                    const blob = await file.text(); // 使用 File.text() 方法读取文本内容
                    const name = file.name;
                    const expName = name.split('.').pop().toLowerCase();
                    return { file, blob, name, expName };
                }));

                resolve(results);
            });

            // 错误处理
            input.addEventListener('error', (e) => {
                document.body.removeChild(input);
                reject(e);
            });
        });
    },
    checkQuestionItem(item) {
        let re = []
        if (!item.stems) re.push('没有题干')
        if (item.type === '选择' && (!item.options.A || !item.options.B || !item.options.C || !item.options.D)) re.push('选项不全')
        if (item.type === '选择' && item.optionAType === 'image' && !item.options.A.startsWith('data:image')) re.push('选项A不是图片')
        if (item.type === '选择' && item.optionBType === 'image' && !item.options.B.startsWith('data:image')) re.push('选项B不是图片')
        if (item.type === '选择' && item.optionCType === 'image' && !item.options.C.startsWith('data:image')) re.push('选项C不是图片')
        if (item.type === '选择' && item.optionDType === 'image' && !item.options.D.startsWith('data:image')) re.push('选项D不是图片')
        if (!item.answer) {
            re.push('没有答案')
        } else {
            let haveA = Boolean(item.answer.indexOf('A') + 1) ? 1 : 0
            let haveB = Boolean(item.answer.indexOf('B') + 1) ? 1 : 0
            let haveC = Boolean(item.answer.indexOf('C') + 1) ? 1 : 0
            let haveD = Boolean(item.answer.indexOf('D') + 1) ? 1 : 0
            let total = haveA + haveB + haveC + haveD
            if (item.answer.length !== total) {
                re.push('答案中含有其他字符')
            }
        }
        return re
    },
    selectImageAndConvertToBase64() {
        return new Promise((resolve, reject) => {
            // 创建一个隐藏的文件输入元素
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*'; // 只接受图片文件
            input.style.display = 'none';

            // 监听文件选择事件
            input.addEventListener('change', () => {
                const file = input.files[0];
                if (!file) {
                    reject(new Error('未选择文件'));
                    return;
                }

                // 使用 FileReader 读取文件并转换为 Base64
                const reader = new FileReader();
                reader.onload = () => {
                    resolve(reader.result); // 返回 Base64 字符串
                };
                reader.onerror = () => {
                    reject(new Error('读取文件失败'));
                };
                reader.readAsDataURL(file);
            });

            // 触发点击事件，打开文件选择对话框
            document.body.appendChild(input);
            input.click();

            // 移除输入元素
            input.remove();
        });
    },
    generateHTML(form, value) {
        return form.map(item => {
            const fieldValue = value[item.field] || "";
            return `<span style="line-height: 0.8;margin-right:10px" ><span style="color:rgb(0,120,215)" >${item.title}</span>：${fieldValue}</span>`;
        }).join(" ");
    },
    forms: {
        question: {
            add(callBack = () => { }, cancelCallBack = () => { }) {
                const ques = {
                    stems: '',
                    options: {
                        A: '', B: '', C: '', D: ''
                    },
                    optionTypes: {
                        A: 'multipleText', B: 'multipleText', C: 'multipleText', D: 'multipleText'
                    },
                    analysis: '',
                    answer: '',
                    img: ''
                }
                useStore().showFormDialog('添加题目', [

                ], [
                    {
                        field: 'stems',
                        title: '题干',
                        type: 'multipleText',
                        wholeLine: true
                    },
                    {
                        field: 'img',
                        title: '题图',
                        type: 'image',
                        wholeLine: true
                    },
                    {
                        field: 'type',
                        title: '类型',
                        type: [{
                            title: '选择',
                            value: '选择'
                        }, {
                            title: '论述',
                            value: '论述'
                        }]
                    },
                    {
                        field: 'optionAType',
                        title: '选项A类型',
                        type: [
                            {
                                title: '文本',
                                value: 'multipleText'
                            },
                            {
                                title: '图像',
                                value: 'image'
                            },
                        ],
                        wholeLine: true,
                        changeForm(value, form) {
                            for (let i = 0; i < form.length; i++) {
                                if (form[i].field === 'optionA') {
                                    form[i].type = value.optionAType
                                    break
                                }
                            }
                            return form
                        }
                    },
                    {
                        field: 'optionA',
                        title: '选项A',
                        type: ques.optionTypes.A,
                        wholeLine: true
                    },
                    {
                        field: 'optionBType',
                        title: '选项B类型',
                        type: [
                            {
                                title: '文本',
                                value: 'multipleText'
                            },
                            {
                                title: '图像',
                                value: 'image'
                            },
                        ],
                        wholeLine: true,
                        changeForm(value, form) {
                            for (let i = 0; i < form.length; i++) {
                                if (form[i].field === 'optionB') {
                                    form[i].type = value.optionBType
                                    break
                                }
                            }
                            return form
                        }
                    },
                    {
                        field: 'optionB',
                        title: '选项B',
                        type: ques.optionTypes.B,
                        wholeLine: true
                    },
                    {
                        field: 'optionCType',
                        title: '选项C类型',
                        type: [
                            {
                                title: '文本',
                                value: 'multipleText'
                            },
                            {
                                title: '图像',
                                value: 'image'
                            },
                        ],
                        wholeLine: true,
                        changeForm(value, form) {
                            for (let i = 0; i < form.length; i++) {
                                if (form[i].field === 'optionC') {
                                    form[i].type = value.optionCType
                                    break
                                }
                            }
                            return form
                        }
                    },
                    {
                        field: 'optionC',
                        title: '选项C',
                        type: ques.optionTypes.C,
                        wholeLine: true
                    },
                    {
                        field: 'optionDType',
                        title: '选项D类型',
                        type: [
                            {
                                title: '文本',
                                value: 'multipleText'
                            },
                            {
                                title: '图像',
                                value: 'image'
                            },
                        ],
                        wholeLine: true,
                        changeForm(value, form) {
                            for (let i = 0; i < form.length; i++) {
                                if (form[i].field === 'optionD') {
                                    form[i].type = value.optionDType
                                    break
                                }
                            }
                            return form
                        }
                    },
                    {
                        field: 'optionD',
                        title: '选项D',
                        type: ques.optionTypes.D,
                        wholeLine: true
                    },
                    {
                        field: 'answer',
                        title: '答案',
                        type: 'multipleText',
                        wholeLine: true
                    },
                    {
                        field: 'analysis',
                        title: '解析',
                        type: 'multipleText',
                        wholeLine: true
                    },
                ], ques, false, (value, fm) => {
                    value.options.A = value.optionA
                    value.options.B = value.optionB
                    value.options.C = value.optionC
                    value.options.D = value.optionD

                    fm.forEach(item => {
                        if (item.field === 'optionA') value.optionTypes.A = item.type
                        if (item.field === 'optionB') value.optionTypes.B = item.type
                        if (item.field === 'optionC') value.optionTypes.C = item.type
                        if (item.field === 'optionD') value.optionTypes.D = item.type
                    })

                    value.optionAType = value.optionTypes.A
                    value.optionBType = value.optionTypes.B
                    value.optionCType = value.optionTypes.C
                    value.optionDType = value.optionTypes.D
                    callBack(value, fm)
                }, true, cancelCallBack)
            },
            edit(item = {}, callBack = () => { }) {
                let e = {
                    item
                }
                useStore().showFormDialog('编辑题目', [

                ], [
                    {
                        field: 'stems',
                        title: '题干',
                        type: 'multipleText',
                        wholeLine: true
                    },
                    {
                        field: 'img',
                        title: '题图',
                        type: 'image',
                        wholeLine: true
                    },
                    {
                        field: 'type',
                        title: '类型',
                        type: [{
                            title: '选择',
                            value: '选择'
                        }, {
                            title: '论述',
                            value: '论述'
                        }]
                    },
                    {
                        field: 'optionAType',
                        title: '选项A类型',
                        type: [
                            {
                                title: '文本',
                                value: 'multipleText'
                            },
                            {
                                title: '图像',
                                value: 'image'
                            },
                        ],
                        wholeLine: true,
                        changeForm(value, form) {
                            for (let i = 0; i < form.length; i++) {
                                if (form[i].field === 'optionA') {
                                    form[i].type = value.optionAType
                                    break
                                }
                            }
                            return form
                        }
                    },
                    {
                        field: 'optionA',
                        title: '选项A',
                        type: e.item.optionTypes.A,
                        wholeLine: true
                    },
                    {
                        field: 'optionBType',
                        title: '选项B类型',
                        type: [
                            {
                                title: '文本',
                                value: 'multipleText'
                            },
                            {
                                title: '图像',
                                value: 'image'
                            },
                        ],
                        wholeLine: true,
                        changeForm(value, form) {
                            for (let i = 0; i < form.length; i++) {
                                if (form[i].field === 'optionB') {
                                    form[i].type = value.optionBType
                                    break
                                }
                            }
                            return form
                        }
                    },
                    {
                        field: 'optionB',
                        title: '选项B',
                        type: e.item.optionTypes.B,
                        wholeLine: true
                    },
                    {
                        field: 'optionCType',
                        title: '选项C类型',
                        type: [
                            {
                                title: '文本',
                                value: 'multipleText'
                            },
                            {
                                title: '图像',
                                value: 'image'
                            },
                        ],
                        wholeLine: true,
                        changeForm(value, form) {
                            for (let i = 0; i < form.length; i++) {
                                if (form[i].field === 'optionC') {
                                    form[i].type = value.optionCType
                                    break
                                }
                            }
                            return form
                        }
                    },
                    {
                        field: 'optionC',
                        title: '选项C',
                        type: e.item.optionTypes.C,
                        wholeLine: true
                    },
                    {
                        field: 'optionDType',
                        title: '选项D类型',
                        type: [
                            {
                                title: '文本',
                                value: 'multipleText'
                            },
                            {
                                title: '图像',
                                value: 'image'
                            },
                        ],
                        wholeLine: true,
                        changeForm(value, form) {
                            for (let i = 0; i < form.length; i++) {
                                if (form[i].field === 'optionD') {
                                    form[i].type = value.optionDType
                                    break
                                }
                            }
                            return form
                        }
                    },
                    {
                        field: 'optionD',
                        title: '选项D',
                        type: e.item.optionTypes.D,
                        wholeLine: true
                    },
                    {
                        field: 'answer',
                        title: '答案',
                        type: 'multipleText',
                        wholeLine: true
                    },
                    {
                        field: 'analysis',
                        title: '解析',
                        type: 'multipleText',
                        wholeLine: true
                    },
                ], e.item, false, (value, fm) => {
                    value.options.A = value.optionA
                    value.options.B = value.optionB
                    value.options.C = value.optionC
                    value.options.D = value.optionD

                    fm.forEach(item => {
                        if (item.field === 'optionA') value.optionTypes.A = item.type
                        if (item.field === 'optionB') value.optionTypes.B = item.type
                        if (item.field === 'optionC') value.optionTypes.C = item.type
                        if (item.field === 'optionD') value.optionTypes.D = item.type
                    })

                    value.optionAType = value.optionTypes.A
                    value.optionBType = value.optionTypes.B
                    value.optionCType = value.optionTypes.C
                    value.optionDType = value.optionTypes.D
                    callBack(value, fm)
                }, true, () => {
                    useStore().hideFormDialog()
                })
            }
        }
    },
    createVirtualFile(content, fileName = "file.txt", mimeType = "text/plain") {
        const blob = new Blob([content], { type: mimeType });
        const blobUrl = URL.createObjectURL(blob);
        const file = new File([blob], fileName, { type: mimeType });
        return new Promise((resolve) => {
            const reader = new FileReader();
            reader.onloadend = () => {
                resolve({
                    base64: reader.result.split(",")[1],
                    file: file,
                    blobUrl: blobUrl
                });
            };
            reader.readAsDataURL(blob);
        });
    },
    async readClipboardImageAsBase64() {
        function blobToPngDataURL(blob) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0);
                    const pngDataUrl = canvas.toDataURL('image/png');
                    resolve(pngDataUrl);
                };
                img.onerror = err => reject(err);

                // 兼容 Firefox 拒绝跨源 blob 读取
                img.crossOrigin = 'anonymous';
                img.src = URL.createObjectURL(blob);
            });
        }

        // 1. 检查异步 Clipboard API 支持与权限
        if (navigator.clipboard && navigator.permissions) {
            try {
                const status = await navigator.permissions.query({ name: 'clipboard-read' });
                if (status.state === 'denied') {
                    return null;
                }
            } catch {
                // 忽略权限错误，继续尝试读取
            }

            // 2. 使用 clipboard.read() 读取 image 类型内容
            try {
                const items = await navigator.clipboard.read();
                for (const item of items) {
                    const type = item.types.find(t => t.startsWith('image/'));
                    if (type) {
                        const blob = await item.getType(type);
                        return await blobToPngDataURL(blob); // ✅ 转成 PNG 格式
                    }
                }
            } catch (err) {
                // 无法访问剪贴板，继续降级
            }
        }

        // 3. 降级方案：监听粘贴事件
        return await new Promise(resolve => {
            function onPaste(e) {
                document.removeEventListener('paste', onPaste);
                const file = Array.from(e.clipboardData.files)
                    .find(f => f.type.startsWith('image/'));
                if (file) {
                    blobToPngDataURL(file).then(resolve).catch(() => resolve(null));
                } else {
                    resolve(null);
                }
            }
            document.addEventListener('paste', onPaste);
            // 你可以在这里提示用户按 Ctrl+V 粘贴图像
            // alert('请按 Ctrl+V 粘贴图片');
        });
    }
}

const check = {
    isArray(e) {
        return Array.isArray(e)
    },
    isInt(e) {
        return (typeof (e) == 'number') && (parseInt(e) == e)
    },
    isNumber(e) {
        return (typeof (e) == 'number')
    },
    isString(e) {
        return typeof (e) == 'string'
    },
    throwError(reason) {
        throw new Error(reason)
    }
}

export default to
